De Type.GetProperties methode
Een eigenschap kan gereflecteerd worden als die tenminste één accessor heeft die
public
is. Anders wordt de eigenschap beschouwd als private
, en moet je BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static
gebruiken om de eigenschap te reflecteren.Bron
Microsoft Developer Network, Type.GetProperties Method (BindingFlags)
Stappenplan
- Open het project met de naam adodotnet in Visual Studio (je kan dat eventueel ook in een ander project uitproberen).
- We maken gebruik van de BLL klasse voor de tabel
EventCategory
(BLL EventCategory). - In de klasse Learing voeg je de volgende methoden toe:
ReflectPropertiesTryOut
:public static void ReflectPropertiesTryOut() { // loop through properties using reflection // https://msdn.microsoft.com/en-us/library/kyaxdd3x(v=vs.110).aspx Type t = typeof(FricFrac.Bll.EventCategory); // Get the public properties. PropertyInfo[] propInfos = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); Console.WriteLine("The number of public properties: {0}.\n", propInfos.Length); // Display the public properties. DisplayPropertyInfo(propInfos); // Get the nonpublic properties. PropertyInfo[] propInfos1 = t.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance); Console.WriteLine("The number of non-public properties: {0}.\n", propInfos1.Length); // Display all the nonpublic properties. DisplayPropertyInfo(propInfos1); }
DisplayPropertyInfo
:public static void DisplayPropertyInfo(PropertyInfo[] propInfos) { // Display information for all properties. foreach (var propInfo in propInfos) { bool readable = propInfo.CanRead; bool writable = propInfo.CanWrite; Console.WriteLine(" Property name: {0}", propInfo.Name); Console.WriteLine(" Property type: {0}", propInfo.PropertyType); Console.WriteLine(" Read-Write: {0}", readable & writable); if (readable) { MethodInfo getAccessor = propInfo.GetMethod; Console.WriteLine(" Visibility: {0}", GetVisibility(getAccessor)); } if (writable) { MethodInfo setAccessor = propInfo.SetMethod; Console.WriteLine(" Visibility: {0}", GetVisibility(setAccessor)); } Console.WriteLine(); } }
GetVisibility
:public static String GetVisibility(MethodInfo accessor) { if (accessor.IsPublic) return "Public"; else if (accessor.IsPrivate) return "Private"; else if (accessor.IsFamily) return "Protected"; else if (accessor.IsAssembly) return "Internal/Friend"; else return "Protected Internal/Friend"; }
- Roep de
ReflectPropertiesTryOut
methode op in deMain
functie van Program.cs (zet de methodeTestMySqlConnector
in commentaar):using System; namespace AdoDotNet { class Program { public static void Main(string[] args) { Console.WriteLine("Leren werken met ADO.NET in .NET Core!"); // Learning.TestMySqlConnector(); Learning.ReflectPropertiesTryOut(); Console.ReadKey(); } } }
- Met dit als resultaat:
2017-09-15 12:02:05